/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataAccess.DataAccessFacade;
import DomainModel.ClassWork;
import DomainModel.Course;
import DomainModel.Grade;
import DomainModel.LetterGrade;
import DomainModel.Role;
import DomainModel.Schedule;
import DomainModel.Section;
import DomainModel.Semester;
import DomainModel.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DomainModel.*;
import DataAccess.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Mershack
 */
public class EnterClassWorkGradeController extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        if (user == null || user.getRole() != Role.PROF) {
            request.getRequestDispatcher("/login").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        loadData(request, response);
    }
    
    private void loadData(HttpServletRequest request, HttpServletResponse response) {
       try {
            int sectionId = Integer.parseInt(request.getParameter("sectionId"));
            int classWorkId = Integer.parseInt(request.getParameter("classWorkId"));
            DataAccessFacade dataAccessFacade = DataAccessFacade.getInstance();
            
            List<StudentAndGrade> studentAndGrades = dataAccessFacade.getSectionGrades(sectionId, classWorkId);
            Section section = dataAccessFacade.getSectionById(sectionId);
            ClassWork classwork = dataAccessFacade.getClassWorkById(classWorkId);
            request.setAttribute("studentAndGrades", studentAndGrades);
            request.setAttribute("section", section);
            request.setAttribute("classWork", classwork);
            request.getRequestDispatcher("/WEB-INF/grs/enterClassWorkGrades.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        //get the data from the form for all the students and save it in  the database.

        String actionBackToClassWorks = request.getParameter("backToClassWorks");
        if (actionBackToClassWorks != null) {
            String sectionId = request.getParameter("sectionId");
            response.sendRedirect("viewClassWorks?sid=" + sectionId);
            return;
        }

        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);
        
        //get the sectionId
        int sectionId = Integer.valueOf(request.getParameter("sectionId"));
        //get the classworkId
        int classWorkId = Integer.valueOf(request.getParameter("classWorkId"));

        //get the student ids
        int studentIds_newGrade[] = convertStringArrayToIntArray(request.getParameterValues("studentId_newGrade"));
        //get the points earned
        int pointsEarned_newGrade[] = convertStringArrayToIntArray(request.getParameterValues("pointsEarned_newGrade"));
        //commentGiven
        String comments_newGrade[] = request.getParameterValues("comments_newGrade");
        
        //get the student ids
        int studentIds_editedGrade[] = convertStringArrayToIntArray(request.getParameterValues("studentId_editableGrade"));
        //get the points earned
        int pointsEarned_editedGrade[] = convertStringArrayToIntArray(request.getParameterValues("pointsEarned_editableGrade"));
        //commentGiven
        String comments_editedGrade[] = request.getParameterValues("comments_editableGrade");

        int gradeId_editedGrade[] = convertStringArrayToIntArray(request.getParameterValues("gradeId_editableGrade"));


        //insert or update grades
        try {
            ClassWork classWork = DataAccessFacade.getInstance().getClassWorkById(classWorkId);
            DataAccessFacade dataAccessFacade = DataAccessFacade.getInstance();

            String errMsg = "";
            if (studentIds_newGrade != null) {
                //insert grades
                List<Grade> grades = createGradesList(studentIds_newGrade, null, pointsEarned_newGrade, comments_newGrade, classWork);
                errMsg = validateGrades(grades);
                if (errMsg.isEmpty()) {
                    dataAccessFacade.insertClassGrades(grades);
                }
            }
            if (errMsg.isEmpty() && studentIds_editedGrade != null) {
                //update grades
                List<Grade> grades = createGradesList(studentIds_editedGrade, gradeId_editedGrade, pointsEarned_editedGrade, comments_editedGrade, classWork);
                errMsg = validateGrades(grades);
                if (errMsg.isEmpty()) {
                    dataAccessFacade.updateClassGrades(grades);
                }
            }

            if (errMsg.isEmpty()) {
                messages.put("success", "Grades saved successfully.");
            }
            else {
                messages.put("error", errMsg);
            }
            
            // load data and redirect to the same page
            loadData(request, response);
//            request.getRequestDispatcher("/grs/viewClassWorkGrades").forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private String validateGrades(List<Grade> grades) {
        for (Grade grade : grades) {
            String validationMsg = grade.validate();
            if (!validationMsg.isEmpty()) {
                return validationMsg;
            }
        }
        return "";
    }
    
    private List<Grade> createGradesList(int studentsId[], int gradesId[], int pointsEarned[], String comments[], ClassWork classWork) {
        List<Grade> grades = new LinkedList<>();
        for (int i = 0; i < studentsId.length; i++) {
            User student = new User(studentsId[i], null, null, null, null, Role.STUD);
            Grade grade = new Grade((gradesId == null) ? 0 : gradesId[i], classWork, pointsEarned[i], student, comments[i]);
            grades.add(grade);
        }
        
        return grades;
    }

    private int[] convertStringArrayToIntArray(String[] strArray) {
        if (strArray != null) {
            int[] intArray = new int[strArray.length];

            for (int i = 0; i < strArray.length; i++) {
                if (strArray[i].isEmpty()) {
                    intArray[i] = -1;
                } else {
                    intArray[i] = Integer.parseInt(strArray[i]);
                }
            }

            return intArray;
        }

        return null;
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
